<?php


require_once("functions.php");
$db = connect_db();

$out = get_header();

$sql = "select * from languages order by language ASC";
$res = mysql_query($sql, $db);
$lang = array();
while(($row = mysql_fetch_array($res)) !== FALSE) 
	$lang[$row['id']] = $row['language'];

$id = $_GET['id'];
$action = $_GET['action'];
if ($action == 'edit' && is_numeric($id)) {
	$sql = "select * from `values` where variable_id = $id";
	$res = mysql_query($sql, $db);
	if($res === FALSE) {
		echo mysql_error();
		$action = 'new';	
	} else {
		$vals = array();
		while(($row = mysql_fetch_array($res)) !== FALSE) {
			$vals[$row['language_id']] = array (0=>$row['id'], 1=>$row['value'], 2=>$row['value2']);
		}
	}
} else if ($action == 'update'  && isset($_GET['value'])) {
	foreach ($_GET['value'] as $l => $val) {
		$sql = "select id from `values` where variable_id=$id and language_id=$l limit 1";
		$res = mysql_query($sql, $db);
		if ($res == FALSE)
			die (mysql_error());
		$val_id = @mysql_result($res, 0,0);
		$v = mysql_real_escape_string($val);
		if (isset ($_GET['value2'][$l]))
			$v2 = mysql_real_escape_string($_GET['value2'][$l]);
		else 
			$v2 = NULL;
		if ($val_id !== FALSE) {
			$sql = "update `values` set language_id=$l, variable_id=$id, value='$v', value2='$v2' where id=$val_id";
		} else {
			$sql = "insert into `values` (language_id, variable_id, value, value2) values ($l, $id, '$v', '$v2')";
		}
		$res = mysql_query($sql, $db);
	}
	header("Location: view_all.php");
} else if ($action == 'new') {
	;
}

$sql = "select extra_variable, variable from fields where id = $id";
$res = mysql_query($sql, $db);
if($res === FALSE)
	die ("Row not found");
$row = mysql_fetch_array($res);
if ($row === FALSE) 
	die ("Row not found");

$evar = $row['extra_variable'];
$var = $row['variable'];

$out .= '<h2>Values $LN['. $var . ']' . ($evar!=''?"[$evar]":'') . "</h2>\n";
$out .= '<form method="get" action="edit_values.php">'. "\n";

$out .= '<input type="hidden" name="id" value="' . $id  . "\"/>\n";
$out .= '<input type="hidden" name="action" value="update"/>' . "\n";

//var_dump($vals);

$out .= '<table>';
$out .= "<tr><th>Language<th>value<th>Optional 2nd value</tr>";
foreach($lang as $lid=>$l) {
	$out .= "<tr>";
	$val = htmlentities (isset($vals[$lid][1])? $vals[$lid][1] : '');
	$val2 = htmlentities (isset($vals[$lid][2])? $vals[$lid][2] : '');
	
	$out .= "<td>" . ucwords($l) . ":";
	$out .= "<td><input type=\"text\" name=\"value[$lid]\" value=\"$val\"/>\n";
	$out .= "<td>==> <input type=\"text\" name=\"value2[$lid]\" value=\"$val2\" size=\"80\"/>\n";
	$out .= "<tr/>";
}
$out .= '</table>';
$out .= "<br><input type=\"submit\" value=\"submit\" name=\"submit\"/>\n";
$out .= "</form>\n";


$out .= get_footer();


echo $out;


?>
